package com.xe;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import groovy.servlet.ServletBinding;
import groovy.servlet.TemplateServlet;
import groovy.text.Template;

public class XETemplateServlet extends TemplateServlet{

	@Override
	protected File getScriptUriAsFile(HttpServletRequest request) {
		System.out.println("XETemplateServlet.getScriptUriAsFile" + getScriptUri(request));
		return null;
	}

/**/
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        if (verbose) {
            log("Creating/getting cached template...");
        }

        //
        // Get the template source file handle.
        //
        Template template;
        long getMillis;
        String name;
        
        File file = getScriptUriAsFile(request);
        if (file != null) {
            name = file.getName();
            if (!file.exists()) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return; // throw new IOException(file.getAbsolutePath());
            }
            if (!file.canRead()) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Can not read \"" + name + "\"!");
                return; // throw new IOException(file.getAbsolutePath());
            }
            getMillis = System.currentTimeMillis();
            template = getTemplate(file);
            getMillis = System.currentTimeMillis() - getMillis;
        } else {
            name = super.getScriptUri(request);
            URL url = servletContext.getResource(name);
            getMillis = System.currentTimeMillis();
            template = getTemplate(url);
            getMillis = System.currentTimeMillis() - getMillis;
        }

        //
        // Create new binding for the current request.
        //
        ServletBinding binding = new ServletBinding(request, response, servletContext);
        setVariables(binding);

        //
        // Prepare the response buffer content type _before_ getting the writer.
        // and set status code to ok
        //
        response.setContentType(CONTENT_TYPE_TEXT_HTML + "; charset=" + encoding);
        response.setStatus(HttpServletResponse.SC_OK);

        //
        // Get the output stream writer from the binding.
        //
        Writer out = (Writer) binding.getVariable("out");
        if (out == null) {
            out = response.getWriter();
        }

        //
        // Evaluate the template.
        //
        if (verbose) {
            log("Making template \"" + name + "\"...");
        }
        // String made = template.make(binding.getVariables()).toString();
        // log(" = " + made);
        long makeMillis = System.currentTimeMillis();
        template.make(binding.getVariables()).writeTo(out);
        makeMillis = System.currentTimeMillis() - makeMillis;

        boolean generateBy=true;
		if (generateBy) {
            StringBuffer sb = new StringBuffer(100);
            sb.append("\n<!-- Generated by Groovy TemplateServlet [create/get=");
            sb.append(Long.toString(getMillis));
            sb.append(" ms, make=");
            sb.append(Long.toString(makeMillis));
            sb.append(" ms] -->\n");
            out.write(sb.toString());
        }

        //
        // flush the response buffer.
        //
        response.flushBuffer();

        if (verbose) {
            log("Template \"" + name + "\" request responded. [create/get=" + getMillis + " ms, make=" + makeMillis + " ms]");
        }

    }/**/
	
}
